package handler

import (
	"encoding/json"
	"platform-master/cache"
	"platform-master/model"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {

	name := c.PostForm("name")
	desc := c.PostForm("desc")

	if name == "" || desc == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段为空",
		})
		return
	}

	var a model.User
	err := model.DB.Create(&a).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return

}

func Adds(c *gin.Context) {

	aid := c.Query("aid")

	var a model.Type
	//SELECT
	//*
	//	FROM
	//types
	//LEFT JOIN app_types ON app_types.id = aid
	//WHERE
	//app_types = ?

	model.DB.Table("a").
		Select("LEFT JOIN app_types ON app_types.id = aid").
		Where("app_types = ?", aid).
		Debug().
		Find(&a)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return

}

func List(c *gin.Context) {

	var a model.App

	redis_list_sys := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_sys).Result()

	if result == "" {
		model.DB.Find(&a)
		jsonData, _ := json.Marshal(&a)
		cache.Rdb.Set(cache.Ctx, redis_list_sys, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &a)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": a,
	})
	return

}
